package com.jmp.security.client;

import com.jmp.base.dto.AccountAppIdRequest;
import com.jmp.base.dto.AccountCompanyKeyRequest;
import com.jmp.base.dto.AccountResponse;
import com.jmp.feign.AccountFeign;
import com.jmp.security.base.ClientDetail;
import com.jmp.security.base.ClientDetailService;
import com.jmp.security.base.RequestDetail;
import one.stand.advice.ResultEnum;
import one.stand.mapper.SecurityClientMapperExt;
import one.stand.model.ResultModel;
import one.stand.model.SecurityClient;
import one.stand.util.AssertUtil;

import java.util.Objects;

public class CompanyKeyClientDetailService implements ClientDetailService {
    private AccountFeign accountFeign;
    private SecurityClientMapperExt securityClientMapperExt;

    public CompanyKeyClientDetailService(AccountFeign accountFeign, SecurityClientMapperExt securityClientMapperExt) {
        this.accountFeign = accountFeign;
        this.securityClientMapperExt = securityClientMapperExt;
    }

    @Override
    public ClientDetail get(RequestDetail requestDetail) {
        AssertUtil.nonNull(requestDetail.getCompanyKey(), ResultEnum.PARAM_CHECK);

        ResultModel<AccountResponse> accountResponseResultModel;
        SecurityClient securityClient = null;
        if (Objects.nonNull(requestDetail.getClientEnum())) {
            securityClient = securityClientMapperExt.selectByName(requestDetail.getClientEnum().getCode());
            AssertUtil.nonNull(securityClient, ResultEnum.PARAM_CHECK);

            AccountAppIdRequest accountCompanyKeyRequest = AccountAppIdRequest.builder()
                    .appId(securityClient.getWxAppId())
                    .build();
            accountResponseResultModel = accountFeign.getByAppId2(accountCompanyKeyRequest);
            AssertUtil.isTrue(accountResponseResultModel);
            AssertUtil.nonNull(accountResponseResultModel.getData(), "未购买服务，请联系客服");
        } else {
            AccountCompanyKeyRequest accountCompanyKeyRequest = AccountCompanyKeyRequest.builder()
                    .companyKey(requestDetail.getCompanyKey())
                    .loginEnum(requestDetail.getLoginEnum())
                    .build();
            accountResponseResultModel = accountFeign.getCompanyKeyDefaultIfNull(accountCompanyKeyRequest);
            AssertUtil.isTrue(accountResponseResultModel);
            AssertUtil.nonNull(accountResponseResultModel.getData(), "未购买服务，请联系客服");
            AssertUtil.isTrue(requestDetail.getCompanyKey().equals(accountResponseResultModel.getData().getCompanyKey()), "未购买服务，请联系客服");
        }

        return ClientDetail.builder()
                .companyKey(requestDetail.getCompanyKey())
                .companyAccountModel(accountResponseResultModel.getData())
                .securityClient(securityClient)
                .build();
    }
}
